package com.knowledgegraph.repository;

import com.knowledgegraph.entity.NodeRelation;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface NodeRelationRepository extends JpaRepository<NodeRelation, Long> {
    
    List<NodeRelation> findBySourceNodeId(Long sourceNodeId);
    
    List<NodeRelation> findByTargetNodeId(Long targetNodeId);
    
    List<NodeRelation> findByRelationType(String relationType);
    
    @Query("SELECT nr FROM NodeRelation nr WHERE nr.sourceNode.id = :sourceId AND nr.targetNode.id = :targetId")
    List<NodeRelation> findBySourceAndTarget(@Param("sourceId") Long sourceId, @Param("targetId") Long targetId);
    
    @Query("SELECT nr FROM NodeRelation nr WHERE " +
           "(nr.sourceNode.id = :nodeId OR nr.targetNode.id = :nodeId)")
    List<NodeRelation> findAllRelationsForNode(@Param("nodeId") Long nodeId);
    
    @Query("SELECT DISTINCT nr.relationType FROM NodeRelation nr")
    List<String> findAllRelationTypes();
    
    @Query("SELECT COUNT(nr) FROM NodeRelation nr WHERE nr.relationType = :relationType")
    Long countByRelationType(@Param("relationType") String relationType);
    
    @Query("SELECT nr FROM NodeRelation nr WHERE " +
           "nr.sourceNode.id IN :nodeIds OR nr.targetNode.id IN :nodeIds")
    List<NodeRelation> findRelationsForNodes(@Param("nodeIds") List<Long> nodeIds);
    
    @Query("SELECT nr FROM NodeRelation nr WHERE nr.weight >= :minWeight")
    List<NodeRelation> findByWeightGreaterThanEqual(@Param("minWeight") Double minWeight);
}